#!/usr/bin/expect -f

# 设置超时时间
set timeout 300

# 获取命令行参数
set server_ip [lindex $argv 0]
set username [lindex $argv 1]
set ssh_port [lindex $argv 2]
set password [lindex $argv 3]

# 连接到服务器并安装Java 17
spawn ssh -p $ssh_port $username@$server_ip

# 等待密码提示
expect "password:"
send "$password\r"

# 等待登录完成
expect "$ "

# 更新包列表
send "sudo apt update\r"
expect "password for $username:"
send "$password\r"
expect "$ "

# 安装Java 17
send "sudo apt install -y openjdk-17-jdk\r"
expect "password for $username:"
send "$password\r"
expect "$ "

# 设置JAVA_HOME环境变量
send "echo 'export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64' >> ~/.bashrc\r"
expect "$ "

send "echo 'export PATH=\$JAVA_HOME/bin:\$PATH' >> ~/.bashrc\r"
expect "$ "

# 重新加载环境变量
send "source ~/.bashrc\r"
expect "$ "

# 验证Java版本
send "java -version\r"
expect "$ "

# 退出SSH连接
send "exit\r"
expect eof 